package com.link.play.fit.ai.ui.weightcontrol.ac

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.databinding.AcWeighControlPbBinding
import com.link.play.fit.ai.ui.guide.BasePageFragment
import com.link.play.fit.ai.ui.guide.ChooseWeightFg
import com.link.play.fit.ai.ui.guide.GoalFg
import com.link.play.fit.ai.ui.guide.HeightWeightFg
import com.link.play.fit.ai.ui.guide.ReachGoalFg
import com.link.play.fit.ai.ui.guide.WorkoutsFg
import com.link.play.fit.ai.utils.HealthUtils.convertCmToFtIn
import com.link.play.fit.ai.utils.HealthUtils.convertKgToLbs
import com.link.play.fit.ai.utils.HealthUtils.covertFtInToCm
import com.link.play.fit.ai.utils.convertLbsToKg
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 * 间歇性禁食流程
 */
class WeighControlPbAc : BaseActivity<AcWeighControlPbBinding>(AcWeighControlPbBinding::inflate) {


    val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(this)[WeighControlViewModel::class.java]
    }

    var currentIndex = 0
    private val heightWeightFg by lazy {
        HeightWeightFg()
    }
    private val goalFg by lazy {
        GoalFg()
    }
    private val workoutsFg by lazy {
        WorkoutsFg()
    }
    private val chooseWeightFg by lazy {
        ChooseWeightFg()
    }
    private val reachGoalFg by lazy {
        ReachGoalFg()
    }

    private val fragments: MutableList<Fragment> by lazy {
        mutableListOf(
            heightWeightFg,
            goalFg,
            workoutsFg,
            chooseWeightFg,
            reachGoalFg
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        fragments.forEachIndexed { index, fragment ->
            (fragment as BasePageFragment<*>).pageIndex = index
        }
        binding.pb.max = fragments.size
        initViewPager2()

        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {

            when (currentIndex) {
                0 -> {
                    finish()
                    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
                }

                else -> {
                    binding.viewPager2.setCurrentItem(currentIndex - 1, true)
                }
            }
        }

        binding.tvNext.setOnClickListener {

            when (currentIndex) {

                heightWeightFg.pageIndex -> {
                    viewModel.userGuideState.update {
                        val new = it.copy(id = it.id + 1)

                        if (it.imperialMetric) {//公制
                            new.weightLbs = convertKgToLbs(it.weightKg)

                            val ftIn = convertCmToFtIn(it.heightCm.toDouble())
                            new.heightFt = ftIn.first
                            new.heightIn = ftIn.second
                        } else {
                            val kg = convertLbsToKg(it.weightLbs)
                            Log.e(TAG, "switchCompat kg=$kg")
                            new.weightKg = kg

                            val cm = covertFtInToCm(it.heightFt, it.heightIn)
                            new.heightCm = cm
                        }
                        new
                    }
                    binding.viewPager2.setCurrentItem(currentIndex + 1, true)
                }


                goalFg.pageIndex -> {
                    if (viewModel.userGuideState.value.weighControlMethod == 0 &&
                        viewModel.userGuideState.value.goal != 2
                    ) {
//                        Toast.makeText(this, "断食只能减肥", Toast.LENGTH_SHORT).show()
                        showTip()
                        return@setOnClickListener
                    }

                    viewModel.userGuideState.update {
                        when (it.goal) {
                            0 -> {
                                it.goalWeightKg = it.weightKg + 10
                                it.goalWeightLbs = it.weightLbs + 10
                            }

                            1 -> {
                                it.goalWeightKg = it.weightKg
                                it.goalWeightLbs = it.weightLbs
                            }

                            2 -> {
                                it.goalWeightKg = it.weightKg - 10
                                it.goalWeightLbs = it.weightLbs - 10
                            }
                        }
                        it.copy(id = it.id + 1)
                    }
                    binding.viewPager2.setCurrentItem(currentIndex + 1, true)
                }

                chooseWeightFg.pageIndex -> {
                    val data = viewModel.userGuideState.value
//                    Log.e(TAG, "断食 data=$data")
                    if (viewModel.userGuideState.value.weighControlMethod == 0) {
                        if (data.goalWeightKg >= data.weightKg || data.goalWeightLbs >= data.weightLbs) {
//                        Toast.makeText(this, "断食只能减肥", Toast.LENGTH_SHORT).show()
                            showTip()
                            return@setOnClickListener
                        }
                    }

                    viewModel.userGuideState.update {
                        val new = it.copy(id = it.id + 1)
                        if (it.imperialMetric) {//公制
                            new.goal = if (it.weightKg < it.goalWeightKg) {
                                0
                            } else if (it.weightKg > it.goalWeightKg) {
                                2
                            } else {
                                1
                            }
                        } else {
                            new.goal = if (it.weightLbs < it.goalWeightLbs) {
                                0
                            } else if (it.weightLbs > it.goalWeightLbs) {
                                2
                            } else {
                                1
                            }
                        }

                        new
                    }

                    binding.viewPager2.setCurrentItem(currentIndex + 1, true)

                }

                reachGoalFg.pageIndex -> {
                    val data = viewModel.userGuideState.value
                    goToAc(WeightControlDailyAc::class.java) {
                        Log.e(TAG, "data=$data")
                        putExtra("data", data)
                    }
                    overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left)
                }

                else -> {
                    binding.viewPager2.setCurrentItem(currentIndex + 1, true)
                }
            }
        }

    }

    private fun initViewPager2() {
        binding.viewPager2.run {
            isUserInputEnabled = false
            adapter = object : FragmentStateAdapter(this@WeighControlPbAc) {
                override fun getItemCount(): Int {
                    return fragments.size
                }

                override fun createFragment(position: Int): Fragment {
                    return fragments[position]
                }
            }
        }
        binding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }

            override fun onPageSelected(position: Int) {
                currentIndex = position
                changeAcUI(position)
            }
        })
    }

    private fun changeAcUI(position: Int) {
        binding.pb.progress = position + 1
    }

    private fun showTip() {
        if (binding.cardTip.isVisible) {
            return
        }
        binding.cardTip.visibility = View.VISIBLE
        lifecycleScope.launch(Dispatchers.Main) {
            delay(1500)
            binding.cardTip.visibility = View.INVISIBLE
        }
    }
}